package com.openstack4j.qx.imp;


import java.util.ArrayList;
import java.util.List;

import org.openstack4j.api.Builders;
import org.openstack4j.api.OSClient.OSClientV2;
import org.openstack4j.api.compute.ServerService;
import org.openstack4j.model.common.ActionResponse;
import org.openstack4j.model.compute.Action;
import org.openstack4j.model.compute.Flavor;
import org.openstack4j.model.compute.RebootType;
import org.openstack4j.model.compute.Server;
import org.openstack4j.model.compute.ServerCreate;
import org.openstack4j.model.compute.ServerUpdateOptions;
import org.openstack4j.model.compute.builder.QuotaSetUpdateBuilder;
import org.openstack4j.model.storage.block.Volume;
import org.openstack4j.openstack.OSFactory;
import org.openstack4j.openstack.compute.domain.NovaQuotaSetUpdate;
import org.openstack4j.openstack.compute.domain.NovaQuotaSetUpdate.QuotaSetUpdateConcreteBuilder;
import org.openstack4j.openstack.compute.internal.ServerServiceImpl;

import com.openstack4j.qx.VMController;
import com.openstack4j.qx.pojo.BaseResp;
import com.openstack4j.qx.pojo.VMInfoSet;
import com.openstack4j.qx.pojo.VMResourceInfo;
import com.openstack4j.qx.pojo.VMResp;
import com.openstack4j.qx.pojo.VMStatusResp;


public class VMControllerImp implements VMController {

	
	
	/**
	 * 创建虚拟机
	 */
	public VMResp CreateVM(String ParamFlag, String ResourceTemplateID, VMResourceInfo vMResourceInfo, String AppID,
			String AppName, int Count, String Security) {
		
		
		//实例化创建虚拟机返回  实体对象
		VMResp vMResp =new VMResp();
		List<VMInfoSet> list_vMResp=new ArrayList();
				
		
		//登录认证
		OSClientV2 os = OSFactory.builderV2()
                .endpoint("http://10.50.0.11:5000/v2.0")
                .credentials("admin","ADMIN_PASS")
                .tenantName("admin")
                .authenticate();
		
		
		//解析XML文件
		
		
		for(int i=0;i<Count;i++){
	
			//创建虚拟机
			List<String> list_network=new ArrayList();
			list_network.add("127c1dd2-0218-4eaf-83b1-09b31c7ddade");
		
			//create server
			ServerCreate sc = Builders.server().name("baater2").networks(list_network)
				.flavor("2").image("3ee9e4d2-356d-4f6d-ac0e-6252d5c6930d").build();
			//boot server
			Server server = os.compute().servers().boot(sc);
		
		
			
			//实例化返回值
			VMInfoSet vm=new VMInfoSet();
			
			//设置返回值VMResp中的值
			vm.setOperationIP(server.getAccessIPv4());
			
			//判断VM status 的string值改为int
			if(server.getVmState()=="active"){
				vm.setStatus(2);
			}else if(server.getVmState()=="building"){
				vm.setStatus(1);
			}else{
				vm.setStatus(0);
			}
			
			vm.setVlanID(server.getAccessIPv4());
			vm.setVMName(server.getTenantId());
			
			list_vMResp.add(vm);
		
		
		
		}
		
		//VMResp的所有值放回到VMResp对象中
		vMResp.setVMInfo(list_vMResp);
		return vMResp;
	}

	
	
	
	/**
	 * 操作虚拟机
	 */
	public BaseResp ActVM(String VMID, int ActType) {
		//登录认证
		OSClientV2 os = OSFactory.builderV2()
                .endpoint("http://10.50.0.11:5000/v2.0")
                .credentials("admin","ADMIN_PASS")
                .tenantName("admin")
                .authenticate();
		//通过参数虚拟机ID，对其做操作		
		Server server = os.compute().servers().get(VMID);
		
		//实例化返回值信息
		BaseResp baseResp = new BaseResp();
		/*
		 * 操作虚拟机
		 * 1：启动 start server
			2：暂停 
			3：恢复
			4：停止
			5：重启
		 */
		
		String result = null;
		if(ActType == 1){
			//  start a Server    
			ActionResponse ar = os.compute().servers().action(server.getId(), Action.START);
			//判断虚拟机操作，并设置返回值。
			if(ar.isSuccess()){
				result = "成功启动了虚拟机"+server.getId();
			}else{
				result = ar.getFault();    
				// 返回值为：  Cannot 'start' instance 9a7baf31-d925-4998-a41b-468a98a8449f while it is in vm_state active
			}
			
		}else if (ActType == 2){
			// Suspend a Server
			ActionResponse ar = os.compute().servers().action(server.getId(), Action.SUSPEND);
			//判断虚拟机操作，并设置返回值。
			if(ar.isSuccess()){
				result = "成功暂停了虚拟机"+server.getId();
			}else{
				result = ar.getFault();
			}
		}else if (ActType == 3){
			// Resume a Server
			ActionResponse ar = os.compute().servers().action(server.getId(), Action.RESUME);
			//判断虚拟机操作，并设置返回值。
			if(ar.isSuccess()){
				result = "成功回复虚拟机"+server.getId();
			}else{
				result = ar.getFault();
			}
			
		}else if (ActType == 4){
			// stop a Server
			ActionResponse ar = os.compute().servers().action(server.getId(), Action.STOP);
			//判断虚拟机操作，并设置返回值。
			if(ar.isSuccess()){
				result = "成功停止虚拟机"+server.getId();
			}else{
				result = ar.getFault();
			}
			
		}else if (ActType == 5){
			// reboot a Server
			ActionResponse ar = os.compute().servers().reboot(server.getId(), RebootType.SOFT);
			//判断虚拟机操作，并设置返回值。
			if(ar.isSuccess()){    //&& server.getVmState() == 'avtive';
				result = "成功重启虚拟机"+server.getId();
			}else{
				result = ar.getFault();
			}
			
		}
		
		//给返回值赋值
		baseResp.setFaultstring(result);
		//返回对象值
		return baseResp;
	}

	
	/**
	 * 删除虚拟机
	 */
	public BaseResp DeleteVM(String VMID) {
		//登录认证
		OSClientV2 os = OSFactory.builderV2()
                .endpoint("http://10.50.0.11:5000/v2.0")
                .credentials("admin","ADMIN_PASS")
                .tenantName("admin")
                .authenticate();
		//删除指定ID的虚拟机
		ActionResponse ar = os.compute().servers().delete(VMID);
		
		
        //定义一个result局部变量
        String result = null;
           //判断返回值
	       if(ar.isSuccess()){
	    	   result="删除虚拟机成功！";
	       }
        
		//实例化返回值对象
        BaseResp baseResp = new BaseResp(); 
		
        //设置返回值
        baseResp.setFaultstring(result);
		
        //返回内容
		return baseResp;
	}
	
	
	
	/**
	 * 更改虚拟机
	 */
	public BaseResp ModifyVM(String VMID, VMResourceInfo vMResourceInfo) {
		//登录认证
		OSClientV2 os = OSFactory.builderV2()
                .endpoint("http://10.50.0.11:5000/v2.0")
                .credentials("admin","ADMIN_PASS")
                .tenantName("admin")
                .authenticate();

		Server server = os.compute().servers().get(VMID);
		
		//创建临时flavor
		Flavor flavor = Builders.flavor()
                .name("__临时资源__")
                .ram(vMResourceInfo.getMemorySize())
                .vcpus(vMResourceInfo.getCPUNum())
                .build();

		os.compute().flavors().create(flavor);
		
	    //按照flavor配额更改指定的虚拟机
		os.compute().servers().resize(server.getId(), flavor.getId());
		
		// 删除临时flavor
		os.compute().flavors().delete(flavor.getId());
		
		
		//创建参数 int vMResourceInfo.getOSSize() 一个磁盘
		for(int i=0;i<vMResourceInfo.getVSCSIAdaNum();i++){
			Volume volume = os.blockStorage().volumes()
		             .create(Builders.volume()
		                .name(vMResourceInfo.getVMName()+"的磁盘")
		                .description("更新"+vMResourceInfo.getVMName()+"的磁盘")
//		                .imageRef("imageId")
		                .bootable(true)
		                .build()
		             );
			
			//实例化ServerService 
			ServerService serverService = new ServerServiceImpl();
			
			//虚拟机ID，磁盘ID和设备名字
			serverService.attachVolume(VMID, volume.getId(), "/dev/vdb");  
		}
 
		
		
		
		
		
		VMInfoSet vMInfoSet = new VMInfoSet();
		vMInfoSet.setVMName(server.getName());
		vMInfoSet.setOperationIP(server.getAccessIPv4());
		vMInfoSet.setVMID(VMID);
		
		if(server.getVmState()=="active"){
			vMInfoSet.setStatus(2);
		}else if(server.getVmState()=="building"){
			vMInfoSet.setStatus(1);
		}else{
			vMInfoSet.setStatus(0);
		}

		return vMInfoSet;
	}

	
	
	/**
	 * 查询虚拟机
	 */
	public BaseResp QueryVMStatus(String VMID) {
		
		
		//登录认证
		OSClientV2 os = OSFactory.builderV2()
                .endpoint("http://10.50.0.11:5000/v2.0")
                .credentials("admin","ADMIN_PASS")
                .tenantName("admin")
                .authenticate();
		
		
		// list server by id
		Server server = os.compute().servers().get(VMID);
		
		
		//实例化返回值对象
		VMStatusResp vMStatusResp = new VMStatusResp(); 
		
		//定义一个变量，并进行判断来设置返回内容
		int tmp = 0;
		if(server.getVmState() != "active"){
			tmp = 1;
		}else{
			tmp = 2;
		}
		
		//设置返回值
        vMStatusResp.setOperationIP(server.getAccessIPv4());
        vMStatusResp.setStatus(tmp);
        vMStatusResp.setVMID(server.getId());
        vMStatusResp.setVlanID(server.getTenantId());
        
        //返回对象值
		return vMStatusResp;
		
		
	}

	
	
	/**
	 * 备份虚拟机
	 */
	public BaseResp BackupVM(String VMID) {
		//登录
		OSClientV2 os = OSFactory.builderV2()
                .endpoint("http://10.50.0.11:5000/v2.0")
	            .credentials("admin","ADMIN_PASS")
	            .tenantName("admin")
	            .authenticate();
		
		// 开始备份虚拟机
		Server server = os.compute().servers().get(VMID);
		
		//定义一个变量，并进行判断返回值内容
		String result;
		if(server.getVmState() == "active"){
			String imageId = os.compute().servers().createSnapshot(server.getId(), server.getName()+"备份");
			result = "成功备份虚拟机 " + imageId;
		}else{
			result = "无法备份虚拟机" + server.getId();
		}
		
		//实例化返回值对象
		BaseResp baseResp = new BaseResp();
		//设置返回值内容
		baseResp.setFaultstring(result);
		//返回对象
		return baseResp;
	}

}
